package restapi

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitverse.ru/tokuara/impleo/restapi/configs"
	"gitverse.ru/tokuara/impleo/restapi/routers"
)

func Run(cfg configs.Config) {
	var runChan = make(chan os.Signal, 1)

	ctx, cancel := context.WithTimeout(
		context.Background(),
		time.Duration(cfg.Server.Timeout.Server),
	)
	defer cancel()

	server := &http.Server{
		Addr:         cfg.Server.Host + ":" + cfg.Server.Port,
		Handler:      routers.InitRouter(),
		ReadTimeout:  time.Duration(cfg.Server.Timeout.Read) * time.Second,
		WriteTimeout: time.Duration(cfg.Server.Timeout.Write) * time.Second,
		IdleTimeout:  time.Duration(cfg.Server.Timeout.Idle) * time.Second,
	}

	//signal.Notify(runChan, os.Interrupt, syscall.SIGTSTP)
	signal.Notify(runChan, os.Interrupt, syscall.Signal(0x14))

	log.Printf("server is starting on %s\n", server.Addr)

	go func() {
		if err := server.ListenAndServe(); err != nil {
			if err == http.ErrServerClosed {

			} else {
				log.Fatalf("server failed to start due to err^ %v", err)
			}
		}
	}()

	interrupt := <-runChan

	log.Printf("server is shutting down due to %+v\n", interrupt)
	if err := server.Shutdown(ctx); err != nil {
		log.Fatalf("server was unable to gracefully shutdown due to err: %+v", err)
	}
}
